import { createStore } from 'vuex'

export default createStore({
  state: {
    showPage: 0, // 控制显示哪个页面，0为首页，1为登录页
    isLoggedIn: false,
    userName: ''
  },
  getters: {
    isLoggedIn: state => state.isLoggedIn,
    userName: state => state.userName
  },
  mutations: {
    setShowPage(state, val) {
      state.showPage = val
    },
    setUser(state, user) {
      state.isLoggedIn = !!user
      state.userName = user ? user.name : ''
    }
  },
  actions: {
    login({ commit }, user) {
      // 保存用户信息到sessionStorage
      if (user) {
        window.sessionStorage.setItem('token', user.token || '')
        window.sessionStorage.setItem('userName', user.name || '')
        window.sessionStorage.setItem('userId', user.id || '')
      }
      commit('setUser', user)
    },
    logout({ commit }) {
      // 清除 sessionStorage 中的用户信息
      window.sessionStorage.removeItem('token')
      window.sessionStorage.removeItem('userName')
      window.sessionStorage.removeItem('userId')
      commit('setUser', null)
    },
    checkLoginStatus({ commit }) {
      const token = window.sessionStorage.getItem('token')
      const name = window.sessionStorage.getItem('userName')
      
      if (token && name) {
        commit('setUser', { name, token })
      } else {
        commit('setUser', null)
      }
    }
  },
  modules: {
  }
})